import React, { useContext, useEffect, useRef, useState } from 'react';
import cs from 'classnames';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import styles from './style/index.module.less';
import {
  Button,
  Checkbox,
  Dropdown,
  Form,
  Grid,
  Input,
  Menu,
  Message,
  Select,
  Space,
  Spin,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import {
  Action,
  AssignedPerson,
  Transfer,
  orgOther,
} from '@/api/modules/violation';
import {
  AssignedPersonItem,
  RepViolationAction,
  ViolationDetails,
} from '@/api/interface/violation.d';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';
import getUrlParams from '@/utils/getUrlParams';
import { Enums } from '@/api/modules';
import { EnumsRes } from '@/api/interface';
import useStorage from '@/utils/useStorage';
import { IconDown } from '@arco-design/web-react/icon';
import { useHistory } from 'react-router-dom';
import ActionWrapper from '@/components/ActionWrapper';
import useIsMountedRef from '@/utils/useIsMountedRef';
import { useSize } from 'ahooks';
import Status from '@/components/Status';

const { Row, Col } = Grid;
const TextArea = Input.TextArea;
const Option = Select.Option;
const { useForm } = Form;
function Personal({
  refNumber,
  details,
  supportEntities,
  violationLinks,
}: {
  refNumber: string;
  details: ViolationDetails;
  supportEntities: Array<any>;
  violationLinks: any[];
}) {
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);
  const [loading, setLoading] = useState(false);
  const [formData, setFormDta] = useState<RepViolationAction>({
    // sendSms: false,
    // sendBack: false,
    // sendForesight: false,
    // sendLocal: false,
    // sendSAI: false,
    localEmirate: undefined,
    violationType: undefined,
    status: undefined,
    actionTaken: undefined,
    assignedPerson: [],
    assignedPersons: [],
    comments: '',
    supportEntities: [],
    links: [],
  });
  const [form] = useForm();
  const onValuesChange = (
    _: unknown,
    values: React.SetStateAction<RepViolationAction>
  ) => {
    setFormDta(values);
  };
  const router = useHistory();
  const searchParams = new URLSearchParams(location.search);
  const fromPath = searchParams.get('fromPath');
  const handleSave = () => {
    if (violationLinks.length > 0) {
      formData.links = violationLinks.map((a) => a.refNumber);
    }
    form.validate((errors, values) => {
      if (!errors) {
        const params = {
          ...formData,
          refNumber,
          supportEntities: supportEntities,
          assignedPerson: formData.assignedPersons,
        };
        if (params?.comments.trim().length == 0) {
          if (params.hasOwnProperty('sendBack')) {
            params.sendBack = false;
          }
          if (params.hasOwnProperty('sendSms')) {
            params.sendSms = false;
          }
        }
        console.log(params);
        setLoading(true);
        Action(params)
          .then(() => {
            form.resetFields();
            setLoading(false);
            if (fromPath === 'task') {
              router.replace({
                pathname: '/MyTasks',
              });
              return;
            }
            router.replace({
              pathname: '/Violation/List',
            });
          })
          .catch(() => {
            setLoading(false);
          });
      }
    });
  };

  const handleTo = (e) => {
    setLoading(true);

    Transfer({ ...e, refNumber })
      .then(() => {
        form.resetFields();
        setLoading(false);
        Message.success({
          id: 'transfer',
          content: `${t['actions.transfer.success']}${
            e.hasOwnProperty('sendLocal') ? 'ADAA' : 'UAEAA'
          }`,
          duration: 3000,
        });
        if (fromPath === 'task') {
          router.replace({
            pathname: '/MyTasks',
          });
          return;
        }
        router.replace({
          pathname: '/Violation/List',
        });
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    const violationType = details.violationBoxType;
    const violationTypes = violationType ? violationType.map((a) => a.key) : [];

    form.setFieldsValue({
      violationType: violationTypes,
      status: details.status ? details.status.key : undefined,
      actionTaken: details.actionTaken ? details.actionTaken.key : undefined,
      assignedPersons:
        details.assignedPerson &&
        details.assignedPerson.filter((a) => a).map((e) => e && e.id),
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [details]);

  const urlParams = getUrlParams();
  const { settings, userInfo } = useSelector((state: GlobalState) => state);

  const menuWidth = settings.collapsed ? 48 : settings.menuWidth;
  const showMenu = settings.menu && urlParams.menu !== false;
  const paddingLeft = showMenu
    ? rtl
      ? { paddingRight: menuWidth }
      : { paddingLeft: menuWidth }
    : {};

  const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
    violationStatusEnums: [],
    violationTypeEnums: [],
    actionTakenEnums: [],
  });
  const getEnums = async () => {
    try {
      const enumData = await Promise.all([
        Enums({ type: 'ViolationStatusEnums' }),
        Enums({ type: 'ViolationInternalTypeEnums' }),
        Enums({ type: 'ActionTakenEnums' }),
      ]);
      if (isMountedRef.current) {
        setEnums({
          violationStatusEnums: enumData[0].data,
          violationTypeEnums: enumData[1].data,
          actionTakenEnums: enumData[2].data,
        });
      }
    } catch (e) {}
  };

  const [assignedPerson, setAssignedPerson] = useState<
    Array<AssignedPersonItem>
  >([]);
  const getAssignedPerson = async () => {
    try {
      const { data } = await AssignedPerson({});
      if (isMountedRef.current) {
        setAssignedPerson(data);
      }
    } catch (e) {}
  };

  const [orgs, setOrgs] = useState([]);
  const getOrgs = async () => {
    try {
      const { data } = await orgOther({});
      if (isMountedRef.current) {
        setOrgs(data);
      }
    } catch (e) {}
  };

  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    getEnums();
    getAssignedPerson();
    getOrgs();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const templates = [
    'The relevant information is under review. A staff member may contact you, so please keep your contact information available.\n From ADAA',
    'Your Feedback has been reviewed, and we kindly request your presence at the specified location on [DD/MM/YY] at [00:00]. \n Our staff will require your assistance for further investigation.\n Thank you.From ADAA',
    'Please provide the following information: \n 1. Invoice \n 2. Bank statement \n 3. xxx...\n From ADAA(or UAEAA)',
  ];
  const [template, setTemplate] = useStorage(
    `${userInfo.id}_action-template1`,
    JSON.stringify(templates)
  );
  const [templateList, setTemplateList] = useState<Array<any>>(
    JSON.parse(template)
  );

  const saveTemplateItem = () => {
    if (!formData.comments) {
      return;
    }
    let arr = [formData.comments, ...templateList];
    if (arr.length > 5) {
      arr = arr.slice(0, 5);
    }
    setTemplateList(arr);
  };

  const changeTemplate = (e: string) => {
    console.log(e);
    form.setFieldValue('comments', e || '');
  };

  const [expand, _] = useState(true);

  useEffect(() => {
    setTemplate(JSON.stringify(templateList));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [templateList]);

  //实时高度
  const actiomRef = useRef<HTMLDivElement | null>(null);
  const [height, setHeight] = useState(0);

  const size = useSize(actiomRef);
  useEffect(() => {
    if (actiomRef.current) {
      const height = actiomRef.current.clientHeight;
      setHeight(height);
    }
  }, [size]);

  //表单订动态生成，需要监听大小变化
  const actionRowRef = useRef<HTMLDivElement | null>(null);
  const actionSize = useSize(actionRowRef);
  const [maxHeight, setMaxHeight] = useState(0);
  const [minHeight, setMinHeight] = useState(0);
  useEffect(() => {
    if (actionRowRef.current) {
      const children = Array.from(
        actionRowRef.current.children
      ) as HTMLDivElement[];
      const heights = children.map((child) => child.clientHeight);
      const sum = (prev, cur) => prev + Number(cur);
      const maxH = heights.reduce(sum, 0);
      setMaxHeight(maxH);
      const firstNonZeroValue = heights.find((value) => value !== 0);
      setMinHeight(firstNonZeroValue);
    }
  }, [actionSize]);

  const dropList = (
    <Menu
      onClickMenuItem={(key) =>
        handleTo({ sendLocal: true, localEmirate: key })
      }
    >
      {orgs.map((option) => (
        <Menu.Item key={option.id}>{option.name}</Menu.Item>
      ))}
    </Menu>
  );
  // 转单
  const sendTo = () => {
    // ADAA为地方机构，UAEAA为联邦机构
    return details.rawRefNumber ? (
      ''
    ) : details.org.name === 'UAEAA' || details.org.name === 'SAI' ? (
      <ActionWrapper action="violation.detail.sendcasetorelayauthority">
        {details.platformSource !== 'ENT' ? (
          <Dropdown
            droplist={dropList}
            position="bl"
            triggerProps={{ autoAlignPopupWidth: true }}
          >
            <Button
              type="outline"
              className={styles['button']}
              loading={loading}
              loadingFixedWidth
            >
              {t['actions.sendTolocal']}
              <IconDown />
            </Button>
          </Dropdown>
        ) : null}
      </ActionWrapper>
    ) : (
      <ActionWrapper action="violation.detail.sendtosai">
        {details.platformSource !== 'ENT' ? (
          <Space>
            <Button
              type="outline"
              onClick={() => handleTo({ sendSAI: true })}
              className={styles['button']}
              loading={loading}
              loadingFixedWidth
            >
              {t['actions.sendToSAI']}
            </Button>
          </Space>
        ) : null}
      </ActionWrapper>
    );
  };

  //邮件提醒
  const sendSms = () => {
    return (
      <ActionWrapper action="violation.detail.sendsmstoapplicant">
        <Space>
          <Form.Item field="sendSms" style={{ marginBottom: 0 }}>
            <Checkbox
              value={true}
              disabled={formData?.comments.trim().length == 0}
            >
              {t['actions.sms']}
            </Checkbox>
          </Form.Item>
        </Space>
      </ActionWrapper>
    );
  };

  //回复给机构
  const sendBackEntity = () => {
    return (
      <ActionWrapper action="violation.detail.sendbacktoentity">
        <Space>
          <Form.Item field="sendBack" style={{ marginBottom: 0 }}>
            <Checkbox
              value={true}
              disabled={formData?.comments.trim().length == 0}
            >
              {t['actions.sendToEntity']}
            </Checkbox>
          </Form.Item>
        </Space>
      </ActionWrapper>
    );
  };

  return (
    <>
      {/* 占位 */}
      <div className={styles['actions-plan']} style={{ height: height }}></div>
      {/* 内容 */}
      <div className={styles['actions']} style={paddingLeft}>
        <Spin
          loading={loading}
          className={cs(styles['spin'], rtl ? 'rtl' : '')}
        >
          <div className={styles['actions-content']} ref={actiomRef}>
            {minHeight === 0 ? (
              ''
            ) : (
              <div className={styles['actions-head']}>
                <div
                  className={cs(rtl ? 'rtl' : '', styles['actions-head-text'])}
                >
                  {t['actions.actions']}
                </div>
              </div>
            )}

            <div className={cs(styles['block'])}>
              <div style={{ paddingTop: 5 }}></div>
              <Form
                form={form}
                labelAlign="left"
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                initialValues={formData}
                onValuesChange={onValuesChange}
                layout="vertical"
                validateMessages={{
                  required: () => t['empty'],
                }}
                validateTrigger="onBlur"
              >
                <div
                  className={styles['action-row']}
                  style={{
                    height: expand ? `${maxHeight}px` : `${minHeight}px`,
                  }}
                >
                  <div className={styles['action-row']} ref={actionRowRef}>
                    {/* 选择框 */}
                    <Row gutter={24}>
                      <ActionWrapper action="violation.detail.assignedperson">
                        <Col span={6}>
                          <Form.Item
                            // label={t['actions.person']}
                            field="assignedPersons"
                          >
                            <Select
                              triggerProps={{
                                containerScrollToClose: true,
                                autoAlignPopupWidth: false,
                                autoAlignPopupMinWidth: true,
                              }}
                              allowClear
                              showSearch
                              mode="multiple"
                              maxTagCount={1}
                              placeholder={t['actions.person.placeholder']}
                              filterOption={(inputValue, option) =>
                                option.props.children
                                  .toLowerCase()
                                  .indexOf(inputValue.toLowerCase()) >= 0
                              }
                            >
                              {assignedPerson.map((option, index) => (
                                <Option key={index} value={option.id}>
                                  {`${option.name}(${option.count})`}
                                </Option>
                              ))}
                            </Select>
                          </Form.Item>
                        </Col>
                      </ActionWrapper>
                      <ActionWrapper action="violation.detail.classifyviolationtype">
                        <Col span={6}>
                          <Form.Item
                            // label={t['actions.type']}
                            field="violationType"
                          >
                            <Select
                              maxTagCount={1}
                              mode="multiple"
                              allowClear
                              showSearch
                              placeholder={t['actions.type.placeholder']}
                              triggerProps={{
                                containerScrollToClose: true,
                                autoAlignPopupWidth: false,
                                autoAlignPopupMinWidth: true,
                              }}
                              filterOption={(inputValue, option) => {
                                return (
                                  option.props.children
                                    .toLowerCase()
                                    .indexOf(inputValue.toLowerCase()) >= 0
                                );
                              }}
                            >
                              {enums.violationTypeEnums.map((option, index) => (
                                <Option key={index} value={option.key}>
                                  {option.value[lang === 'en-US' ? 'en' : 'ar']}
                                </Option>
                              ))}
                            </Select>
                          </Form.Item>
                        </Col>
                      </ActionWrapper>
                      <ActionWrapper action="violation.detail.violationstatus">
                        <Col span={6}>
                          <Form.Item
                            // label={t['actions.status']}
                            field="status"
                          >
                            <Select
                              placeholder={t['actions.status.placeholder']}
                              triggerProps={{
                                containerScrollToClose: true,
                                autoAlignPopupWidth: false,
                                autoAlignPopupMinWidth: true,
                              }}
                              onChange={() => {
                                form.setFieldsValue({
                                  actionTaken: undefined,
                                });
                              }}
                            >
                              {enums.violationStatusEnums.map(
                                (option, index) => (
                                  <Option key={index} value={option.key}>
                                    <div className={rtl ? 'rtl' : ''}>
                                      <Status status={option?.key}></Status>
                                      {
                                        option.value[
                                          lang === 'en-US' ? 'en' : 'ar'
                                        ]
                                      }
                                    </div>
                                  </Option>
                                )
                              )}
                            </Select>
                          </Form.Item>
                        </Col>
                      </ActionWrapper>
                      <ActionWrapper action="violation.detail.actiontaken">
                        <Col span={6}>
                          <Form.Item
                            // label={t['actions.taken']}
                            field="actionTaken"
                          >
                            <Select
                              allowClear
                              placeholder={t['actions.taken.placeholder']}
                              triggerProps={{
                                containerScrollToClose: true,
                                autoAlignPopupWidth: false,
                                autoAlignPopupMinWidth: true,
                              }}
                            >
                              {enums.actionTakenEnums
                                .filter(
                                  (a) =>
                                    a.key.charAt(0).toUpperCase() ===
                                    (formData.status &&
                                      formData.status.charAt(0).toUpperCase())
                                )
                                .map((option, index) => (
                                  <Option key={index} value={option.key}>
                                    {
                                      option.value[
                                        lang === 'en-US' ? 'en' : 'ar'
                                      ]
                                    }
                                  </Option>
                                ))}
                            </Select>
                          </Form.Item>
                        </Col>
                      </ActionWrapper>
                    </Row>
                    {/* comments提交 */}
                    <Row>
                      <ActionWrapper action="violation.detail.comments">
                        <div className={styles['template']}>
                          <Space>
                            {/* <span className={styles['template-title']}>
                              {t['actions.comments']}
                            </span>
                            <span>|</span> */}
                            <Select
                              triggerProps={{
                                containerScrollToClose: true,
                              }}
                              bordered={false}
                              style={{ width: 250 }}
                              allowClear
                              placeholder={t['actions.chooseTemplate']}
                              onChange={changeTemplate}
                            >
                              {templateList.map((option, index) => (
                                <Option key={index} value={option}>
                                  0{index + 1} {option}
                                </Option>
                              ))}
                            </Select>
                          </Space>
                          <Button
                            className={styles['template-save']}
                            onClick={saveTemplateItem}
                          >
                            {t['actions.saveTemplate']}
                          </Button>
                        </div>
                        <Form.Item field="comments">
                          <TextArea
                            placeholder={t['actions.textArea.placeholder']}
                            autoSize={{ minRows: 1, maxRows: 5 }}
                            maxLength={1000}
                          />
                        </Form.Item>
                      </ActionWrapper>
                    </Row>
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        paddingBottom: 10,
                      }}
                    >
                      <div style={{ flex: 1 }}>
                        {/* COMP-Local */}
                        {details.platformSource == 'COMP' && <>{sendSms()}</>}

                        {/* ENT-Local */}
                        {details.platformSource == 'ENT' && (
                          <>{sendBackEntity()}</>
                        )}
                        {/* INT-Local */}
                        {details.platformSource == 'INT' && <>{sendSms()}</>}
                      </div>
                      <Space className={styles['right-button']} size={20}>
                        {/* COMP-Local */}
                        <div>
                          {details.platformSource == 'COMP' && <>{sendTo()}</>}
                          {details.platformSource == 'ENT' && <>{sendTo()}</>}
                          {details.platformSource == 'INT' && <>{sendTo()}</>}
                        </div>

                        <ActionWrapper action="violation.detail.violation/action">
                          <Button
                            type="primary"
                            onClick={handleSave}
                            className={styles['button']}
                            loading={loading}
                            loadingFixedWidth
                          >
                            {t['actions.save']}
                          </Button>
                        </ActionWrapper>
                      </Space>
                    </div>
                    {/* 共有 */}
                  </div>
                </div>
              </Form>
            </div>
          </div>
        </Spin>
      </div>
    </>
  );
}

export default Personal;
